<template>
  <div class="document-layout">
    <div class="main">
      <div class="layout-container" :class="{ 'toc-hidden': !isTocVisible }">
        <!-- 主内容区域 -->
        <div class="content">
          <Detail
            :document="selectedDocument"
            :current-space-id="currentSpaceId"
            @edit="onDocumentEdit"
            @create="onDocumentSave"
            @delete="onDocumentDelete"
            @select="onDocumentSelect"
            @refresh="onRefresh"
            @toggle-left-drawer="toggleLeftDrawer"
            @toggle-right-drawer="toggleRightDrawer"
          />
        </div>

        <!-- 右侧文档目录 -->
        <div class="document-toc-sidebar" :class="{ 'toc-hidden': !isTocVisible }">
          <!-- 目录内容 -->
          <div class="toc-wrapper" v-show="isTocVisible">
            <div v-if="selectedDocument && selectedDocument.content" class="document-toc">
              <div class="toc-header">
                <h3>目录</h3>
              </div>

              <div class="toc-content">
                <div v-if="tocItems.length === 0" class="toc-empty">
                  <p>暂无目录</p>
                </div>

                <ul v-else class="toc-list">
                  <li
                    v-for="item in tocItems"
                    :key="item.anchor"
                    :class="['toc-item', `toc-level-${item.level}`, { 'toc-active': item.anchor === activeAnchor }]"
                    @click="scrollToHeading(item.anchor)"
                  >
                    <a :href="`#${item.anchor}`" @click.prevent>
                      {{ item.text }}
                    </a>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 左侧抽屉遮罩 -->
      <div 
        class="drawer-overlay left-overlay" 
        v-show="isLeftDrawerOpen"
        @click="closeLeftDrawer"
      ></div>

      <!-- 左侧抽屉 -->
      <div v-if="isMobile()" class="drawer left-drawer" :class="{ 'drawer-open': isLeftDrawerOpen }">
        <div class="drawer-header">
          <h3>文档</h3>
          <button class="drawer-close-btn" @click="closeLeftDrawer">×</button>
        </div>
        <div class="drawer-content">
          <Menu
            ref="mobileSidebarRef"
            :spaces="mobileSpaces"
            :selected-space="mobileCurrentSpace"
            :current-space-id="currentSpaceId"
            :search-query="mobileSearchQuery"
            @space-select="handleMobileSpaceSelect"
            @create-space="handleMobileCreateSpace"
            @create-document="handleMobileCreateDocument"
            @search="handleMobileSearch"
            @document-select="onMobileDocumentSelect"
            @document-edit="onDocumentEdit"
            @document-delete="onDocumentDelete"
            @document-create="onMobileDocumentCreate"
          />
        </div>
      </div>

      <!-- 右侧抽屉遮罩 -->
      <div 
        class="drawer-overlay right-overlay" 
        v-show="isRightDrawerOpen"
        @click="closeRightDrawer"
      ></div>

      <!-- 右侧抽屉 -->
      <div class="drawer right-drawer" :class="{ 'drawer-open': isRightDrawerOpen }">
        <div class="drawer-header">
          <h3>文档目录</h3>
          <button class="drawer-close-btn" @click="closeRightDrawer">×</button>
        </div>
        <div class="drawer-content">
          <div v-if="selectedDocument && selectedDocument.content" class="document-toc">
            <div class="toc-header">
              <h3>目录</h3>
            </div>

            <div class="toc-content">
              <div v-if="tocItems.length === 0" class="toc-empty">
                <p>暂无目录</p>
              </div>

              <ul v-else class="toc-list">
                <li
                  v-for="item in tocItems"
                  :key="item.anchor"
                  :class="['toc-item', `toc-level-${item.level}`, { 'toc-active': item.anchor === activeAnchor }]"
                  @click="scrollToHeading(item.anchor)"
                >
                  <a :href="`#${item.anchor}`" @click.prevent>
                    {{ item.text }}
                  </a>
                </li>
              </ul>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, watch, inject, provide, nextTick } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Detail from '../components/detail.vue'
import Menu from '../components/Menu.vue'
import type { Doc } from '@/modules/doc/types/doc.ts'
import type { NameSpace } from '@/modules/doc/types/namespace.ts'
import { useDoc, useDocDetail } from '@/modules/doc/composables'
import { namespaceApi } from '@/modules/doc/api'
import { toast } from '@/utils/message.ts'
import {isMobile} from "@/utils/AppUtils.ts";

// Toc 相关类型定义
interface TocItem {
  level: number
  text: string
  anchor: string
}

// 使用 composables
const {
  documents,
  fetchDocumentsByNamespace,
  createDocument
} = useDoc()
const { fetchDocumentDetail } = useDocDetail()

// 状态管理
const selectedDocument = ref<Doc | null>(null)
const currentSpaceId = inject('currentSpaceId', ref<string | null>(null))
const injectedOnDocumentSelect = inject<((document: Doc | null) => void) | null>('onDocumentSelect', null)
const injectedOnDocumentEdit = inject<((document: Doc) => void) | null>('onDocumentEdit', null)
const injectedOnDocumentDelete = inject<((id: string) => void) | null>('onDocumentDelete', null)
const isSpaceSwitching = ref(false)
const isTocVisible = ref(false) // 控制右侧目录的显示状态
const isLoadingDocument = ref(false) // 防止重复加载文档

// Toc 相关状态
const tocItems = ref<TocItem[]>([])
const activeAnchor = ref<string>('')
let observer: IntersectionObserver | null = null

// 监听currentSpaceId变化
watch(() => currentSpaceId.value, async (newSpaceId, oldSpaceId) => {
  // 当空间真正发生切换时，清除当前选中的文档
  // Menu.vue 会自动加载新空间的文档并选中第一个
  if (newSpaceId !== oldSpaceId && oldSpaceId !== null && newSpaceId !== null) {
    selectedDocument.value = null
  }
})

// 监听选中文档变化，同步目录显示状态
watch(() => selectedDocument.value, (newDocument) => {
  if (newDocument && newDocument.id !== '-1') {
    // 如果文档有isShowToc设置，使用文档的设置
    if (typeof newDocument.isShowToc === 'boolean') {
      isTocVisible.value = newDocument.isShowToc
    }
  }
}, { immediate: true })

// 监听文档内容变化，生成目录
watch(() => selectedDocument.value?.content, (newContent) => {
  if (newContent) {
    tocItems.value = generateToc(newContent)
    nextTick(() => {
      setupIntersectionObserver()
    })
  } else {
    tocItems.value = []
  }
}, { immediate: true })

// 移动端抽屉状态
const isLeftDrawerOpen = ref(false)
const isRightDrawerOpen = ref(false)

// 移动端侧边栏状态
const mobileSidebarRef = ref()
const mobileSpaces = ref<NameSpace[]>([])
const mobileCurrentSpace = ref<NameSpace | null>(null)
const mobileSearchQuery = ref('')

const route = useRoute()
const router = useRouter()

// 定义emits
const emit = defineEmits<{
  'create-click': [handler: () => void]
}>()

// 切换目录显示状态
const toggleToc = () => {
  isTocVisible.value = !isTocVisible.value
}

// Toc 相关函数
// 生成目录项
const generateToc = (content: string): TocItem[] => {
  const headingRegex = /^(#{1,6})\s+(.+)$/gm
  const items: TocItem[] = []
  let match

  while ((match = headingRegex.exec(content)) !== null) {
    const level = match[1].length
    const text = match[2].trim()
    const anchor = text
      .toLowerCase()
      .replace(/[^\u4e00-\u9fa5a-z0-9\s]/g, '') // 保留中文、英文、数字和空格
      .replace(/\s+/g, '-') // 空格替换为连字符
      .trim()

    items.push({
      level,
      text,
      anchor: anchor || `heading-${items.length}`
    })
  }

  return items
}

// 滚动到指定标题
const scrollToHeading = (anchor: string) => {
  const target = document.getElementById(anchor)
  if (target) {
    target.scrollIntoView({
      behavior: 'smooth',
      block: 'start'
    })
  }
}

// 设置活动锚点的 Intersection Observer
const setupIntersectionObserver = () => {
  if (observer) {
    observer.disconnect()
  }

  observer = new IntersectionObserver(
    (entries) => {
      let visibleEntries = entries.filter(entry => entry.isIntersecting)

      if (visibleEntries.length > 0) {
        // 选择第一个可见的标题
        const topEntry = visibleEntries.reduce((prev, current) => {
          return prev.boundingClientRect.top < current.boundingClientRect.top ? prev : current
        })

        activeAnchor.value = topEntry.target.id
      }
    },
    {
      rootMargin: '-20% 0px -80% 0px' // 当标题在屏幕上方20%位置时激活
    }
  )

  // 观察所有标题元素
  nextTick(() => {
    if (tocItems.value) {
      tocItems.value.forEach(item => {
        const element = document.getElementById(item.anchor)
        if (element && observer) {
          observer.observe(element)
        }
      })
    }
  })
}

// 移动端抽屉控制函数
const toggleLeftDrawer = () => {
  isLeftDrawerOpen.value = !isLeftDrawerOpen.value
  // 关闭右侧抽屉
  if (isLeftDrawerOpen.value) {
    isRightDrawerOpen.value = false
  }
}

const closeLeftDrawer = () => {
  isLeftDrawerOpen.value = false
}

const toggleRightDrawer = () => {
  isRightDrawerOpen.value = !isRightDrawerOpen.value
  // 关闭左侧抽屉
  if (isRightDrawerOpen.value) {
    isLeftDrawerOpen.value = false
  }
}

const closeRightDrawer = () => {
  isRightDrawerOpen.value = false
}

// 移动端侧边栏处理方法
const loadMobileSpaces = async () => {
  try {
    const result = await namespaceApi.getAll()
    mobileSpaces.value = result
    
    // 同步当前空间
    if (currentSpaceId.value) {
      mobileCurrentSpace.value = result.find((space: NameSpace) => space.id === currentSpaceId.value) || null
    }
  } catch (error) {
    console.error('加载移动端空间列表失败:', error)
  }
}

const handleMobileSpaceSelect = async (command: string) => {
  const space = mobileSpaces.value.find((s: NameSpace) => s.id === command)
  if (space) {
    mobileCurrentSpace.value = space
    currentSpaceId.value = command
    
    // 关闭左侧抽屉
    closeLeftDrawer()
  }
}

const handleMobileCreateSpace = () => {
  console.log('移动端创建空间')
}

const handleMobileCreateDocument = () => {
  if (!currentSpaceId.value) {
    toast.error('请先选择空间')
    return
  }
  
  // 关闭左侧抽屉
  closeLeftDrawer()
  
  // 直接跳转到新建文档页面，传递空间ID作为查询参数
  router.push(`/doc/create?spaceId=${currentSpaceId.value}`)
}

const handleMobileSearch = (query: string) => {
  mobileSearchQuery.value = query
}

const onMobileDocumentSelect = (document: Doc | null) => {
  // 关闭左侧抽屉
  closeLeftDrawer()
  // 调用原有的文档选择方法
  onDocumentSelect(document)
}

const onMobileDocumentCreate = (spaceId?: string) => {
  console.log('移动端文档创建:', spaceId)
}

// 监听当前空间变化，同步移动端数据
watch(() => currentSpaceId.value, async (newSpaceId) => {
  if (newSpaceId) {
    // 同步移动端当前空间
    mobileCurrentSpace.value = mobileSpaces.value.find((space: NameSpace) => space.id === newSpaceId) || null
  }
})

const onDocumentSelect = (document: Doc | null) => {
  if (document === null) {
    // 清除选中状态，回到首页
    selectedDocument.value = null
    // 清除记忆的文档ID
    localStorage.removeItem('last-viewed-document-id')
    router.push('/doc')
    return
  }
  
  selectedDocument.value = document
  // 保存当前文档ID到localStorage
  if (document.id) {
    localStorage.setItem('last-viewed-document-id', document.id.toString())
    // 更新路由，带上文档ID（但要避免在空间切换时触发不必要的跳转）
    if (route.params.id !== document.id.toString()) {
      router.replace(`/doc/${document.id}`)
    }
  }
  
  // 如果是空间切换完成，重置标志
  if (isSpaceSwitching.value) {
    isSpaceSwitching.value = false
  }
  
  // 调用注入的函数，通知父组件
  if (injectedOnDocumentSelect) {
    injectedOnDocumentSelect(document)
  }
}

const onDocumentEdit = (document: Doc) => {
  // 调用注入的函数处理编辑
  if (injectedOnDocumentEdit) {
    injectedOnDocumentEdit(document)
  } else {
    // 备用处理
    router.push(`/doc/edit/${document.id}`)
  }
}

// 处理新文档保存
const onDocumentSave = async (newDocument: Omit<Doc, 'id' | 'createdTime' | 'updatedTime' | 'children'>) => {
  try {
    const createdDocument = await createDocument(newDocument)
    
    // 检查返回的文档是否有效
    if (!createdDocument || !createdDocument.id) {
      console.error('API返回的文档数据无效:', createdDocument)
      toast.error('创建文档失败：返回数据无效')
      return
    }
    
    selectedDocument.value = createdDocument
    // 保存新创建的文档ID到localStorage
    localStorage.setItem('last-viewed-document-id', createdDocument.id.toString())
    router.push(`/doc/${createdDocument.id}`)
  } catch (error) {
    console.error('创建文档失败:', error)
    toast.error('创建文档失败')
  }
}

const onDocumentDelete = (id: string) => {
  // Menu.vue 已经处理了删除接口调用和列表刷新
  // 这里只需要处理额外的业务逻辑

  // 如果删除的是当前选中的文档，清除选择并导航回首页
  if (selectedDocument.value && selectedDocument.value.id === id) {
    selectedDocument.value = null
    // 如果删除的是记忆的文档，清除localStorage记录
    const rememberedId = localStorage.getItem('last-viewed-document-id')
    if (rememberedId === id) {
      localStorage.removeItem('last-viewed-document-id')
    }
    router.push('/doc')
  }

  // 调用注入的函数处理删除后的刷新
  if (injectedOnDocumentDelete) {
    injectedOnDocumentDelete(id)
  }
}

const onRefresh = async () => {
  // 如果有选中的文档，重新加载它
  if (selectedDocument.value && selectedDocument.value.id !== '-1') {
    try {
      const refreshedDocument = await fetchDocumentDetail(selectedDocument.value.id, {
        showLoading: false,
        showError: false
      })
      if (refreshedDocument) {
        selectedDocument.value = {
          ...selectedDocument.value,
          ...refreshedDocument,
          items: refreshedDocument.items || []
        }
      }
    } catch (error) {
      console.error('刷新文档失败:', error)
      toast.error('刷新文档失败')
    }
  }
  
  // 刷新操作现在由左侧菜单的组件处理
}

// 尝试加载记忆的文档，如果没有则加载第一个可用文档
const loadRememberedOrFirstDocument = async () => {
  // 先尝试加载记忆的文档
  const rememberedDocId = localStorage.getItem('last-viewed-document-id')
  if (rememberedDocId) {
    try {
      const document = await fetchDocumentDetail(rememberedDocId, {
        showLoading: false,
        showError: false
      })
      
      if (document) {
        selectedDocument.value = document

        // 如果文档有namespaceId，设置当前空间（只在没有空间ID时设置）
        if (document.namespaceId && !currentSpaceId.value) {
          console.log('[Main] 设置空间ID为记忆文档的空间:', document.namespaceId)
          currentSpaceId.value = document.namespaceId
        }

        // 更新路由到记忆的文档
        router.replace(`/doc/${document.id}`)
      }
      return
    } catch (error) {
      console.warn('记忆的文档不存在，清除记录:', error)
      localStorage.removeItem('last-viewed-document-id')
    }
  }
  
  // 如果记忆的文档无效，则加载第一个可用文档
  await loadFirstAvailableDocument()
}

// 加载第一个可用文档
const loadFirstAvailableDocument = async () => {
  try {
    // 获取所有命名空间
    const namespaces = await namespaceApi.getAll()
    if (namespaces.length === 0) {
      selectedDocument.value = null
      return
    }
    
    // 设置第一个命名空间为当前空间
    const firstNamespace = namespaces[0]
    currentSpaceId.value = firstNamespace.id
    
    // 获取该空间下的文档列表
    await fetchDocumentsByNamespace(firstNamespace.id, {
      flatten: true,
      sort: true
    })
    
    if (documents.value.length === 0) {
      selectedDocument.value = null
      return
    }
    
    // 选择第一个文档
    const firstDocument = documents.value[0]
    const detailDoc = await fetchDocumentDetail(firstDocument.id, {
      showLoading: false,
      showError: false
    })
    
    selectedDocument.value = detailDoc || firstDocument
    
    // 保存当前文档ID到localStorage
    localStorage.setItem('last-viewed-document-id', firstDocument.id.toString())
    // 更新路由到这个文档
    router.replace(`/doc/${firstDocument.id}`)
  } catch (error) {
    console.error('加载默认文档失败:', error)
    selectedDocument.value = null
  }
}

// 根据路由参数加载文档
const loadDocumentFromRoute = async () => {
  // 如果当前路由是收藏页面，不要加载文档
  if (route.path.includes('/favorites')) {
    return
  }
  
  const docId = route.params.id
  
  // 防止重复加载同一个文档
  if (isLoadingDocument.value) {
    return
  }
  
  // 如果已经加载了相同的文档，不需要重复加载
  if (selectedDocument.value && selectedDocument.value.id.toString() === docId) {
    return
  }
  
  if (docId && typeof docId === 'string') {
    try {
      isLoadingDocument.value = true
      const document = await fetchDocumentDetail(docId, {
        showLoading: false,
        showError: false
      })
      
      if (document) {
        selectedDocument.value = document
        // 保存当前文档ID到localStorage
        localStorage.setItem('last-viewed-document-id', document.id.toString())

        // 如果文档有namespaceId，设置当前空间（只在没有空间ID时设置）
        if (document.namespaceId && !currentSpaceId.value) {
          console.log('[Main] 从路由文档设置空间ID:', document.namespaceId)
          currentSpaceId.value = document.namespaceId
        }
      }
    } catch (error) {
      console.error('加载文档失败:', error)
      toast.error('文档不存在或加载失败')
      // 如果文档不存在，且当前有空间ID，让 Menu.vue 自动加载该空间的文档
      if (currentSpaceId.value) {
        console.log('[Main] 文档不存在但有空间ID，等待 Menu 自动加载')
        return
      }
      // 否则尝试加载记忆的文档或第一个可用文档
      await loadRememberedOrFirstDocument()
    } finally {
      isLoadingDocument.value = false
    }
  } else {
    // 如果没有文档ID
    // 如果已经有 currentSpaceId，说明正在切换空间，Menu.vue 会自动加载文档，不需要这里处理
    if (currentSpaceId.value) {
      console.log('[Main] 已有空间ID，跳过加载记忆文档，等待 Menu 自动加载')
      return
    }
    // 只有在完全没有空间ID的情况下，才尝试加载记忆的文档或第一个可用文档
    await loadRememberedOrFirstDocument()
  }
}

// 监听路由变化
watch(() => route.path, (newPath, _oldPath) => {
  // 如果正在切换空间，不要处理路由变化
  if (isSpaceSwitching.value) {
    return
  }
  
  // 如果路由是收藏页面，不要尝试加载文档
  if (newPath.includes('/favorites')) {
    return
  }
  
  // 如果已经有选中文档且ID匹配，就不需要重新加载
  const currentDocId = route.params.id
  if (selectedDocument.value && selectedDocument.value.id.toString() === currentDocId) {
    return
  }
  
  // 加载路由对应的文档
  loadDocumentFromRoute()
})

// 也需要监听路由参数变化
watch(() => route.params.id, (newId, oldId) => {
  if (newId !== oldId && newId) {
    loadDocumentFromRoute()
  }
})

// 向子组件提供toggleToc方法和状态
provide('toggleToc', toggleToc)
provide('isTocVisible', isTocVisible)

// 组件挂载时加载文档
onMounted(() => {
  // 设置页面标题
  document.title = '懒熊文档'
  
  // 加载移动端空间数据
  loadMobileSpaces()
  
  loadDocumentFromRoute()
  // 向父组件发送创建处理函数（空函数，因为已移除顶部新建按钮）
  emit('create-click', () => {})
})

onUnmounted(() => {
  // 清理 Intersection Observer
  if (observer) {
    observer.disconnect()
  }
})
</script>

<style scoped>
.document-layout {
  min-height: 100vh;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.main {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.layout-container {
  flex: 1;
  display: flex;
  min-height: 0;
}

/* Sidebar样式已移除，现在使用主左侧菜单 */

.content {
  flex: 1;
  background: #FFFFFF;
  display: flex;
  flex-direction: column;
  min-width: 0;
  margin-right: 25vw; /* 使用视口宽度单位，为固定目录留出空间 */
}

/* 当目录隐藏时，内容区域占满全宽 */
.layout-container.toc-hidden .content {
  margin-right: 0;
}

.document-toc-sidebar {
  width: 25vw; /* 使用视口宽度单位，与内容区域的margin-right保持一致 */
  flex-shrink: 0;
  background: #F3F3F3;
  border-left: 1px solid #e1e1e1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: fixed;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 100;
  transition: width 0.3s ease;
}

/* 目录隐藏状态 */
.document-toc-sidebar.toc-hidden {
  width: 0;
  border-left: none;
}



/* 目录内容包装器 */
.toc-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}


/* 抽屉遮罩 */
.drawer-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1998;
  backdrop-filter: blur(4px);
}

/* 抽屉基础样式 */
.drawer {
  position: fixed;
  top: 0;
  bottom: 0;
  width: 320px;
  max-width: 85vw;
  background: white;
  z-index: 1999;
  display: flex;
  flex-direction: column;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

/* 左侧抽屉 */
.left-drawer {
  left: 0;
  transform: translateX(-100%);
}

.left-drawer.drawer-open {
  transform: translateX(0);
}

/* 右侧抽屉 */
.right-drawer {
  right: 0;
  transform: translateX(100%);
}

.right-drawer.drawer-open {
  transform: translateX(0);
}

/* 抽屉头部 */
.drawer-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20px;
  border-bottom: 1px solid #e1e1e1;
  background: #f8f9fa;
}

.drawer-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.drawer-close-btn {
  width: 32px;
  height: 32px;
  border: none;
  background: transparent;
  font-size: 24px;
  color: #999;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 6px;
  transition: all 0.2s ease;
}

.drawer-close-btn:hover {
  background: #e9ecef;
  color: #666;
}

/* 抽屉内容 */
.drawer-content {
  flex: 1;
  overflow: hidden;
  padding: 0;
}

.drawer-empty-message {
  text-align: center;
  color: var(--el-text-color-regular);
  font-size: 14px;
  padding: 20px;
  background: var(--el-fill-color-light);
  border-radius: 6px;
}

/* 桌面端显示控制 */
.desktop-only {
  display: block;
}

/* 移动端适配 */
@media (max-width: 768px) {
  /* 隐藏桌面端按钮 */
  .desktop-only {
    display: none !important;
  }
  
  .document-toc-sidebar {
    display: none !important;
  }
  
  /* 内容区域占满全宽 */
  .content {
    width: 100% !important;
    flex: 1;
    margin-right: 0 !important; /* 移动端移除右边距 */
  }
  
  .dark .drawer-header {
    background: #2d2d2d;
    border-bottom-color: #3d3d3d;
  }
  
  .dark .drawer-header h3 {
    color: #e6e6e6;
  }
  
  .dark .drawer-close-btn {
    color: #b3b3b3;
  }
  
  .dark .drawer-close-btn:hover {
    background: #3d3d3d;
    color: #e6e6e6;
  }
}

/* 中等屏幕适配 */
@media (max-width: 1200px) and (min-width: 769px) {
  .document-toc-sidebar {
    width: 25%;
  }
  
  .document-toc-sidebar.toc-hidden {
    width: 0;
    border-left: none;
  }
}

/* 平板端适配 */
@media (max-width: 1024px) and (min-width: 769px) {
  .content {
    width: 100%;
    min-height: 80vh;
  }
  
  .document-toc-sidebar {
    display: none;
  }
}

.dark .document-toc-sidebar {
  background: #1D1D1D;
  border-left-color: #3d3d3d;
}


/* 深色模式平板端适配已简化 */

/* ========== Toc 样式（从 toc.vue 合并） ========== */
.document-toc {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #F3F3F3;
}

.toc-header {
  padding: 1rem;
  border-bottom: 1px solid #e1e1e1;
  flex-shrink: 0;
}

.toc-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.1rem;
  font-weight: 600;
}

.toc-content {
  flex: 1;
  overflow-y: auto;
  padding: 0.5rem 0;
}

.toc-empty {
  padding: 2rem 1rem;
  text-align: center;
  color: #666;
}

.toc-empty p {
  margin: 0;
  font-size: 0.9rem;
}

.toc-list {
  list-style: none;
  margin: 0;
  padding: 0;
}

.toc-item {
  position: relative;
  cursor: pointer;
  transition: all 0.2s ease;
}

.toc-item a {
  display: block;
  padding: 0.4rem 1rem;
  text-decoration: none;
  color: #666;
  font-size: 0.9rem;
  line-height: 1.4;
  border-left: 3px solid transparent;
  transition: all 0.2s ease;
}

.toc-item:hover a {
  color: #42b883;
  background: #f8f9fa;
}

.toc-item.toc-active a {
  color: #42b883;
  border-left-color: #42b883;
  background: #e6f7ff;
  font-weight: 500;
}

/* 不同级别的缩进 */
.toc-level-1 a {
  padding-left: 1rem;
  font-weight: 600;
}

.toc-level-2 a {
  padding-left: 1.5rem;
  font-weight: 500;
}

.toc-level-3 a {
  padding-left: 2rem;
}

.toc-level-4 a {
  padding-left: 2.5rem;
}

.toc-level-5 a {
  padding-left: 3rem;
}

.toc-level-6 a {
  padding-left: 3.5rem;
}

/* 深色模式适配 */
.dark .document-toc {
  background: #1D1D1D;
}

.dark .toc-header {
  border-bottom-color: #3d3d3d;
}

.dark .toc-header h3 {
  color: #e6e6e6;
}

.dark .toc-empty {
  color: #b3b3b3;
}

.dark .toc-item a {
  color: #b3b3b3;
}

.dark .toc-item:hover a {
  color: #42b883;
  background: #2d2d2d;
}

.dark .toc-item.toc-active a {
  color: #42b883;
  background: #42b88333;
}

/* 滚动条样式 */
.toc-content::-webkit-scrollbar {
  width: 6px;
}

.toc-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.toc-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.toc-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.dark .toc-content::-webkit-scrollbar-track {
  background: #2d2d2d;
}

.dark .toc-content::-webkit-scrollbar-thumb {
  background: #555;
}

.dark .toc-content::-webkit-scrollbar-thumb:hover {
  background: #666;
}
</style>